from DBUtil import DBUtils
from bookInfo import Book
from bookInfo import DownLoadInfo
import logging
logging.basicConfig(
    level=logging.INFO
)
class BookOperator(object):
    def __addBook(self,book):
        logging.info("add book:%s" % book.bookName);
        dbUtil = DBUtils();
        conn,cur = dbUtil.connDB();
        insertBookSql = ("insert into book (bookName,bookUrl,bookInfo) values ('%s','%s','%s');"%(book.bookName,book.downLoadUrl,book.mainInfo));
        dbUtil.exeUpdate(conn,cur,insertBookSql);
        dbUtil.connClose(conn,cur);
    def __selectLastBookId(self):
        logging.info("selectLastBookId ");
        dbUtil = DBUtils();
        conn,cur = dbUtil.connDB();
        selectLastBookSql = "select id from book order by id desc limit 1";
        effect_row,cur = dbUtil.exeQuery(cur,selectLastBookSql);
        bookId = cur.fetchone()[0];
        dbUtil.connClose(conn,cur);
        return bookId;
    def __addBookDownLoadInfos(self,downLoadInfos,bookId):
        logging.info("add bookId:%s" % bookId);
        dbUtil = DBUtils();
        conn,cur = dbUtil.connDB();
        for downLoadinfo in downLoadInfos:
            insertBookDownLoadInfo = ("insert into book_down_url (bookId,downName,downUrl) values ('%s','%s','%s');"%(bookId,downLoadinfo.downName,downLoadinfo.downUrl));
            dbUtil.exeUpdate(conn,cur,insertBookDownLoadInfo);
        dbUtil.connClose(conn,cur);
    def addBookInfo(self,book):
        logging.info("add bookInfo:%s" % book.bookName);
        self.__addBook(book);
        bookId = self.__selectLastBookId();
        self.__addBookDownLoadInfos(book.downLoadInfos,bookId);
if __name__ == '__main__':
    bookope = BookOperator();
    book = Book("aaa","yang","cccc");
    book.addDownLoadUrl(DownLoadInfo("aaa.html","书籍"));
    bookope.addBookInfo(book);

